#coding=utf-8
#
# Copyright (C) 2014  NianNian TECH Co., Ltd. All rights reserved.
# Created on May 9, 2014, by Junn
#
from core.views import CustomAPIView
from feedbacks.models import Feedback
from utils import http
from core import codes
from utils.http import JResponse, Response, standard_response
from core.serializers import BaseModelSerializer
from utils.eggs import rename_file
from django.contrib import messages

# feedback for web view
def feedback(req):
    if req.method == 'GET':
        return standard_response('feedback.html',{}, req)
   
    data = {}   
    data['contact'] = req.POST.get('contact', '')
    data['content'] = req.POST.get('content', '')
    
    if not data['content'] or len(data['content'].strip()) < 5:
        messages.add_message(req, messages.ERROR, u'输入内容有点少哦')
        return standard_response('feedback.html',{'status': 0}, req)
        
    if req.user and req.user.is_authenticated():
        data['user'] = req.user
        
    if 'HTTP_X_FORWARDED_FOR' in req.META.keys():
        data['ip'] = req.META['HTTP_X_FORWARDED_FOR']
    else:
        data['ip'] = req.META['REMOTE_ADDR']
        
    try:    
        fb = Feedback(**data)
        fb.save()
    except: 
        messages.add_message(req, messages.ERROR, u'服务器小伙伴歇菜了, 过会儿再试吧 ...')
        return standard_response('feedback.html', {'status': 0}, req)
    
    messages.add_message(req, messages.SUCCESS, u'留言提交成功')
    return standard_response('feedback.html', {'status': 1}, req) 

class FeedbackView(CustomAPIView):
    '''for api view '''
    
    def post(self, req):
        data = {}
        data['contact'] = req.POST.get('contact', '')
        data['content'] = req.POST.get('content', '')
        data['aud'] = req.FILES.get('aud')
        
        if not data['content'] and not data['aud']:
            return JResponse(codes.fmat('params_error', '还没有输入任何反馈内容'))
        
        if data['content'] and len(data['content']) < 5:
            return JResponse(codes.fmat('params_error', ': 反馈内容不少于5个字'))
        
        if req.user and req.user.is_authenticated():
            data['user'] = req.user
            
        if 'HTTP_X_FORWARDED_FOR' in req.META.keys():
            data['ip'] = req.META['HTTP_X_FORWARDED_FOR']
        else:
            data['ip'] = req.META['REMOTE_ADDR']
            
        if data['aud']:    
            rename_file(data['aud'])
                    
        fb = Feedback(**data)
        fb.save()    
        return http.ok()
                    
    
    def get(self, req):
        fbs = Feedback.objects.all()
        return Response(FeedbackSerializer(fbs).data)
        
class FeedbackSerializer(BaseModelSerializer):
    
    class Meta:
        model = Feedback
        fields = ('id', 'contact', 'content', 'user', 'ip', 'created_time')        


